package cn.java76.springboot.demo1.controller;

import cn.java76.springboot.demo1.entity.OVideo;
import cn.java76.springboot.demo1.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@RestController
@RequestMapping("video")
public class VideoController {

    @Value("${laoliu.uploadpath}")
    private String upload = "";

    @PostMapping("add")
    public AjaxResult add(OVideo v, @RequestParam("video") MultipartFile f1, @RequestParam("cover") MultipartFile f2) throws IOException {
        //一个封面图片，一个是视频
        MultipartFile[] files = {f1, f2};//构建一个数组
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<" + Arrays.toString(files));
        for (MultipartFile f : files) {
            if (f.isEmpty())
                continue;
            //>>>上传路径
            String p = upload + "/images";
            File folder = new File(p);
            if (!folder.exists())
                folder.mkdirs();//没有则创建
            String oldName = f.getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf('.'));
            String newName = UUID.randomUUID() + suffix;
            f.transferTo(new File(folder, newName));
            if (f.getName().equals("cover"))
                v.setCoverimg(newName);
            else if (f.getName().equals("video"))
                v.setUrl(newName);
        }

        System.out.println("视频对象的地址是："+v);
        return AjaxResult.success("ok",v);
}

    //加上时间的处理
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm");
        //细化的控制，只控制createtime的转换
        binder.registerCustomEditor(Date.class, "createtime", new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值 }

    }
}
